package com.shiguiwu.springmybatis.spring.property.refresh;

import cn.hutool.db.Db;
import cn.hutool.db.DbUtil;
import cn.hutool.db.Entity;
import com.shiguiwu.springmybatis.spring.property.refresh.BeanRefreshScope;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.core.env.MapPropertySource;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @description: 工具类
 * @author: stone
 * @date: Created by 2021/4/6 22:02
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis.spring.property
 */
public class RefreshConfigUtil {

    public static void updateDb()throws SQLException {

        DbUtil.use().execute("update xxl_config set value = ? where id =2", UUID.randomUUID().toString());

    }

    public static void updateDbConfig(AbstractApplicationContext context) {
        try {
            updateDb();
            refreshMailPropertySource(context);
            BeanRefreshScope.getInstance().clear();
        }
        catch (SQLException e) {
            e.printStackTrace();
        }


    }

    public static void refreshMailPropertySource(AbstractApplicationContext context) throws SQLException {
        //下面是关键的代码
        //1,从db中读取配置
        List<Entity> config = Db.use().findAll("xxl_config");
        Map<String, Object> collect = config.parallelStream()
                .collect(Collectors.toMap(k -> k.getStr("key"), v -> v.getStr("value")));
        MapPropertySource mapPropertySource = new MapPropertySource("mail", collect);
        context.getEnvironment().getPropertySources().addFirst(mapPropertySource);

    }
}
